JavaScript Day1: Java Script Objects

Categories: JavaScript; Tagged with: ; @ November 13th, 2014 22:57
  // define a flight
        var flight = {
            airline: "KLM",
            number: 835,
            departure: {
                city: "SG",
                IATA: "SIN"
            },
            scheduleDays: [1, 2, 5]
        };

        console.log("Flight: ", flight);

        // add new attribute
        flight.code="KLM835";
        console.log("Added code: ", flight);

        // retrieve attribute
        console.log("Retrieve departure city:", flight.departure.city);

        // delete attribute
        console.log("Flight code: ", flight.code);
        delete flight.code;
        console.log("Deleted flight code: ", flight.code);

        // for...in
        for(day in flight.scheduleDays) {
            console.log("for...in: schedule day: ", day);
        }

        // for loop
        for(i = 0; i < flight.scheduleDays.length; i++ ) {
            console.log("Schedule day:", flight.scheduleDays[i], " @ index: " , i);
        }

        // define new function
        var printFlight = function(flight) {
         return "Flight print: " +  flight.airline + " - " + flight.number;
        };

        // initialize new flight via prototype;
        var flight2 = Object.create(flight);
        console.log("Flight2 created based on Flight: " +  printFlight(flight2));

        // add new attribute to the new flight
        flight2.code = "KML836";
        console.log("Flight2.code: ", flight2.code);
        console.log("Flight.code: ", flight.code);

        // update new flight
        flight2.airline = "SIA";
        console.log("Flight.airline: ", flight.airline);
        console.log("Flight2 airline", flight2.airline);

        // update the prototype;
        flight.airline = "BA";
        console.log("Flight.airline: ", flight.airline);
        console.log("Flight2 airline", flight2.airline);

        // type of
        console.log(typeof flight);
        console.log(typeof flight2);
        console.log(typeof flight.scheduleDays[0]);

output:

Flight: 
Object {airline: "KLM", number: 835, departure: Object, scheduleDays: Array[3]}
Added code: 
Object {airline: "KLM", number: 835, departure: Object, scheduleDays: Array[3], code: "KLM835"}
Retrieve departure city: SG
Flight code:  KLM835
Deleted flight code:  undefined for...in: schedule day:  0 for...in: schedule day:  1 for...in: schedule day:  2 Schedule day: 1  @ index:  0 Schedule day: 2  @ index:  1 Schedule day: 5  @ index:  2 Flight2 created based on Flight: Flight print: KLM - 835
Flight2.code:  KML836 Flight.code:  undefined
flight.airline:  KLM Flight2 airline SIA Flight.airline:  BA
Flight2 airline SIA object object number

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.